package com.bjtu.ptsite.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bjtu.ptsite.model.AnnounceRequest;
import com.bjtu.ptsite.model.Result;
import com.bjtu.ptsite.model.User;
import com.bjtu.ptsite.service.impl.AnnounceService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;

import static net.i2p.crypto.eddsa.Utils.bytesToHex;

/**
 * AnnounceController by zehao on 20250605
 * @author Zehao Wang, Junjie Zhang, Yutao Wei
 */
@RestController
@Slf4j
public class AnnounceController {

    @Autowired
    private AnnounceService announceService;

    private static final int MAX_IP_LENGTH = 15;
    private static final String IP_SEPARATOR = ",";

    @GetMapping("/announce/{passKey}")
    public ResponseEntity<byte[]> handleAnnounce(HttpServletRequest request, @PathVariable String passKey,
                                                 @ModelAttribute AnnounceRequest announceRequest) {
        log.info("Received announce request: messageId={}, params={}", passKey, announceRequest);
        String queryString = request.getQueryString();

        String clientIp = processIpRequest();
        log.info("Received announce request: passKey={}, clientIp={}", passKey, clientIp);
        byte[] responseBytes = announceService.handleAnnounce(passKey, announceRequest,clientIp,queryString);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/x-bittorrent"));

        return new ResponseEntity<>(responseBytes, headers, HttpStatus.OK);
    }

    private String processIpRequest() {

        String clientIp;
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        clientIp = request.getHeader("x-real-ip");

        if (isUnknownIp(clientIp)) {
            clientIp = request.getHeader("x-forwarded-for");

        }
        if (isUnknownIp(clientIp)) {
            clientIp = request.getHeader("remote-host");
        }
        if (isUnknownIp(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");

        }
        if (isUnknownIp(clientIp)) {
            clientIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (isUnknownIp(clientIp)) {
            clientIp = request.getRemoteAddr();
        }

        //使用代理，则获取第一个IP地址
        if (StringUtils.isNotBlank(clientIp) && clientIp.length() > MAX_IP_LENGTH) {
            if (clientIp.indexOf(IP_SEPARATOR) > 0) {
                clientIp = clientIp.substring(0, clientIp.indexOf(IP_SEPARATOR));
            }
        }

        return clientIp;
    }

    private static boolean isUnknownIp(String ip) {
        return StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip);
    }
}
